/*
*┌────────────────────────────────────────────────┐
*│　描    述：房源核验管理端应用服务
*│  部    门：质量架构部
*│　作    者：华威                                              
*│　版    本：1.0                                              
*│　创建时间：2020.05.27                        
*└────────────────────────────────────────────────┘
*/
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SOEI.Solution.Application.Contracts.Customized.RoomSourceVerifiy.Dtos;
using SOEI.Solution.DomainEntities.RoomSourceVerifiy.DomainService;
using SOEI.Solution.DomainEntities.RoomSourceVerifiy.Dtos;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;

namespace SOEI.Solution.DomainEntities.RoomSourceVerifiy
{
    /// <summary>
    /// 【扩展模块】  <br/>
    /// 【功能描述】  ：房源核验申请应用服务<br/>
    /// 【创建日期】  ：2020.05.21 <br/>
    /// 【开发人员】  ：static残影<br/>
    ///</summary>
    [ApiExplorerSettings(GroupName = "Manager", IgnoreApi = true)]
    public class RoomVerifyApplyAppService : SolutionAppServiceBase, IRoomVerifyApplyAppService
    {
        /// <summary>
        ///【RoomVerifyApply】仓储层
        /// </summary>
        private readonly IRepository<RoomVerifyApply, long> _roomverifyapplyRepository;

        /// <summary>
        ///【RoomVerifyApply】领域服务
        /// </summary>
        private readonly IRoomVerifyApplyManager _roomverifyapplyManager;

        /// <summary>
        ///【RoomVerifyApply】领域服务
        /// </summary>
        private readonly IRoomVerifyManager _roomverifyManager;

        private readonly IRoomVerifyPropertyManager _roomVerifyPropertyManager;

        public RoomVerifyApplyAppService(
            IRepository<RoomVerifyApply, long> roomverifyapplyRepository,
            IRoomVerifyApplyManager roomverifyapplyManager,
            IRoomVerifyManager roomverifyManager,
            IRoomVerifyPropertyManager roomVerifyPropertyManager

        )
        {
            _roomverifyapplyRepository = roomverifyapplyRepository;
            _roomverifyapplyManager = roomverifyapplyManager;
            _roomverifyManager = roomverifyManager;
            _roomVerifyPropertyManager = roomVerifyPropertyManager;
        }

        #region -------------------------------------------------辅助工具生成---------------------------------------------- 

        /// <summary>
        ///【房源核验】获取分页列表信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task<PagedResultDto<RoomVerifyApplyListDto>> GetPaged(GetRoomVerifyApplysInput input)
        {
            //var query = _roomverifyapplyRepository.GetAll()
            var query = _roomverifyapplyManager.QueryUnionEntityListAsNoTracking()
                          //模糊搜索 字段RoomVerifyCode
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.RoomVerifyCode.Contains(input.FilterText))
                          //模糊搜索 字段StateCode
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.StateCode.Contains(input.FilterText))
                          //模糊搜索 字段Remark
                          .WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.Remark.Contains(input.FilterText))
            ;
            // TODO:根据传入的参数添加过滤条件

            var count = await query.CountAsync();

            var entityList = await query
                    .OrderBy(input.Sorting).AsNoTracking()
                    .PageBy(input)
                    .ToListAsync();

            var entityListDtos = ObjectMapper.Map<List<RoomVerifyApplyListDto>>(entityList);

            return new PagedResultDto<RoomVerifyApplyListDto>(count, entityListDtos);
        }

        /// <summary>
        ///【房源核验】通过指定id获取MemberListDto信息
        /// </summary>
        [AbpAuthorize()]
        public async Task<RoomVerifyApplyListDto> GetById(EntityDto<long> input)
        {

            #region 测试

            var r = await _roomverifyManager.QueryAsNoTracking().Include(x => x.RoomVerifyPropertys).ToListAsync();

            #endregion

            var entity = await _roomverifyapplyRepository.GetAsync(input.Id);

            var dto = ObjectMapper.Map<RoomVerifyApplyListDto>(entity);
            return dto;
        }

        /// <summary>
        ///【房源核验】 获取编辑
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task<GetRoomVerifyApplyForEditOutput> GetForEdit(NullableIdDto<long> input)
        {
            var output = new GetRoomVerifyApplyForEditOutput();
            RoomVerifyApplyEditDto editDto;

            if (input.Id.HasValue)
            {
                var entity = await _roomverifyapplyRepository.GetAsync(input.Id.Value);
                editDto = ObjectMapper.Map<RoomVerifyApplyEditDto>(entity);
            }
            else
            {
                editDto = new RoomVerifyApplyEditDto();
            }
            output.RoomVerifyApply = editDto;
            return output;
        }
        /// <summary>
        ///【房源核验】 添加或者修改的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task CreateOrUpdate(CreateOrUpdateRoomVerifyApplyInput input)
        {

            if (input.RoomVerifyApply.Id.HasValue)
            {
                await Update(input.RoomVerifyApply);
            }
            else
            {
                await Create(input.RoomVerifyApply);
            }
        }
        /// <summary>
        ///【房源核验】新增
        /// </summary>
        [AbpAuthorize()]
        protected virtual async Task<RoomVerifyApplyEditDto> Create(RoomVerifyApplyEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = ObjectMapper.Map<RoomVerifyApply>(input);
            //调用领域服务
            entity = await _roomverifyapplyManager.CreateAsync(entity);

            var dto = ObjectMapper.Map<RoomVerifyApplyEditDto>(entity);
            return dto;
        }

        /// <summary>
        ///【房源核验】编辑
        /// </summary>
        [AbpAuthorize()]
        protected virtual async Task Update(RoomVerifyApplyEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新
            var key = input.Id.Value;
            var entity = await _roomverifyapplyRepository.GetAsync(key);
            //  input.MapTo(entity);
            //将input属性的值赋值到entity中
            ObjectMapper.Map(input, entity);
            await _roomverifyapplyManager.UpdateAsync(entity);
        }

        /// <summary>
        ///【房源核验】删除信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize()]
        public async Task Delete(EntityDto<long> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除
            await _roomverifyapplyManager.DeleteAsync(input.Id);
        }

        /// <summary>
        ///【房源核验】 批量删除Member的方法
        /// </summary>
        [AbpAuthorize()]
        public async Task BatchDelete(List<long> input)
        {
            // TODO:批量删除前的逻辑判断，是否允许删除
            await _roomverifyapplyManager.BatchDelete(input);
        }

        #endregion

        #region -------------------------------------------------用户自定义------------------------------------------------
        /*请在此扩展应用服务实现*/

        /// <summary>
        ///  检查输入的项目如：产权证号 是否可用
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<GetVerifyCheckResultOutput> ForCheck(CheckVerifyInput input)
        {
            var output = new GetVerifyCheckResultOutput();
            // 1. 是否创建过产权信息
            output.HasRoomVerify = await _roomverifyManager.IsExistAsync(input.CertificateCode);
            // 2.产权是否可以交易（需要验证）
            output.IsTradable = true;
            // 3.是否存在我的机构申请信息

            // 4.成功了则返回
            output.Checked = true; // 验证通过
            output.Message = "当前产权允许交易，可以协助产权人进行资料提交！";
            return output;


            //var output = new GetVerifyCheckResultOutput();
            //// 1. 是否创建过产权信息
            //output.HasRoomVerify = await _roomverifyManager.IsExistAsync(input.CertificateNum);
            //// 2.产权是否可以交易（需要验证）
            //output.IsTradable = true;
            //// 3.是否存在我的机构申请信息

            //// 4.成功了则返回
            //output.Checked = true; // 验证通过
            //output.Message = "当前产权允许交易，可以协助产权人进行资料提交！";

            //output.PropertyOwnerName = input.Name;
            //output.PropertyOwnerIdentityCard = input.CertificateNum;
            //output.PropertyCardNum = input.PropertyNum;
            //output.HouseLocated = "陕西省西安市雁塔区xxx";
            //output.PropertyState = "正常";
            //return output;

        }

        /// <summary>
        /// 登记，业务受理服务
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<RoomVerifyApplyListDto> Register(ApplyInput input)
        {

            var userEntity = await this.GetCurrentUserAsync();
            // 1. 生成一个全新的房源核验信息
            var entityRoomVerify = await _roomverifyManager.FindByCertificateCodeAsync(input.PropertyCardNum);
            if (entityRoomVerify == null)
            {
                entityRoomVerify = new RoomVerify();
                // 产权证号必须要有
                entityRoomVerify.CertificateCode = input.PropertyCardNum;
                entityRoomVerify.StateCode = "1";
                entityRoomVerify.PropertyCardNum = input.PropertyCardNum;
                entityRoomVerify.HouseLocated = input.HouseLocated;
                entityRoomVerify.PropertyState = 0;  //0: 正常

                await _roomverifyManager.CreateAsync(entityRoomVerify);
            }

            var entityRoomVerifyProperty = await _roomVerifyPropertyManager.FindByRoomVerifyIdAsync(entityRoomVerify.Id);
            if (entityRoomVerifyProperty == null)
            {
                entityRoomVerifyProperty = new RoomVerifyProperty();
                entityRoomVerifyProperty.PropertyOwnerName = input.PropertyOwnerName;
                entityRoomVerifyProperty.PropertyOwnerIdentityCard = input.PropertyOwnerIdentityCard;
                entityRoomVerifyProperty.RoomVerifyId = (int)entityRoomVerify.Id;
            }

            // 2. 为当前经济机构创建一条申请记录
            var entityRoomVerifyApply = await _roomverifyapplyManager.FindByRoomVerifyIDAsync(entityRoomVerify.Id, 1);
            if (entityRoomVerifyApply == null)
            {
                entityRoomVerifyApply = new RoomVerifyApply();
                entityRoomVerifyApply.OrganizeID = 1;
                entityRoomVerifyApply.RoomVerifyID = entityRoomVerify.Id;
                entityRoomVerifyApply.StateCode = "1"; // 草稿
                entityRoomVerifyApply.VerifyUserID = userEntity.Id;
                var aaa = await _roomverifyapplyManager.CreateAsync(entityRoomVerifyApply);
            }
            entityRoomVerifyApply.RoomVerify = entityRoomVerify;
            var dto = ObjectMapper.Map<RoomVerifyApplyListDto>(entityRoomVerifyApply);
            return dto;
        }
        #endregion
    }
}
